import React, {Fragment} from "react";
import {Button, Form, Input} from "antd";
import {connect} from "react-redux";
import {actions} from '../store';
import './style.css'
import Validator from "@/util/Validator";
import {AuthPasswd, errorMsg, successMsg, warnMsg} from "@/util/global";
import EventBus from "@/util/EventBus";
import {actions as UserAction} from '@/store/common/user';
import {LockOutlined, MailOutlined, MobileOutlined, NumberOutlined, UserOutlined} from '@ant-design/icons';
import {sendEmailValidation} from "@/api/Common";
import {isEmail, isPhone} from "@/util/Regex";

class SignView extends React.Component {

    constructor(props) {
        super(props);
        this.handleSendEmailCode = this.handleSendEmailCode.bind(this);
        this.checkSurePwd = this.checkSurePwd.bind(this);
        this.state = {
            emailCodeTimeOut: null,
        }
    }

    checkSurePwd({}) {

    }

    handleSendEmailCode() {
        if (!this.props.SignEmail) {
            warnMsg("邮箱不能为空！");
            return;
        }
        sendEmailValidation(this.props.SignEmail)
            .then(res => {
                if (res.success) {
                    successMsg("验证码已发送！");
                    this.emailTimer = setInterval(() => {
                        let current = this.state.emailCodeTimeOut;
                        if (current !== null && current !== 0) {
                            this.setState({
                                emailCodeTimeOut: current - 1
                            })
                        } else if (current === null) {
                            this.setState({
                                emailCodeTimeOut: 60
                            })
                        } else {
                            clearInterval(this.emailTimer)
                            this.setState({
                                emailCodeTimeOut: null
                            })
                        }
                    }, 1000)
                }
            })
    }

    componentDidMount() {
        EventBus.addListener('sign', (boolean) => {
            if (boolean === true) {
                this.props.history.push('/login')
            }
        })
    }

    render() {
        const {
            SignAccount,
            SignPassword,
            SignSurePassword,
            SignPhone,
            SignEmail,
            SignMailCode,
            // SignSMSCode,
            changeSignAccount,
            changeSignPassword,
            changeSignSurePassword,
            changeSignPhone,
            changeSignEmail,
            changeSignMailCode,
            // changeSignSMSCode,
            handleSign
        } = this.props;

        function Sign() {
            if (SignPassword !== SignSurePassword) {
                warnMsg("两次密码输入不一致，请确认后再试！")
                return;
            }

            const user = {
                account: SignAccount,
                password: SignPassword,
                phone: SignPhone,
                email: SignEmail,
                mailCode: SignMailCode
            };

            if (Validator(user)) {
                handleSign()
            } else {
                return;
            }
        }

        return (
            <Fragment>
                <Form>
                    <Form.Item name="account"  rules={
                        [
                            {required: false},
                            ({getFieldValue}) => ({
                                validator(_, value) {
                                    if (value === undefined || value === null || value.length === 0){
                                        return Promise.reject(new Error('账号不能为空！'));
                                    }else if (value.length < 8 || value.length > 16) {
                                        return Promise.reject(new Error('请输入8~16位账号！'));
                                    }else if (!/^[0-9a-zA-Z]*$/g.test(value)){
                                        return Promise.reject(new Error('账号只能是英文字母及数字组合！'));
                                    }
                                    return Promise.resolve();
                                },
                            }),
                        ]}
                        hasFeedback
                    >
                        <Input prefix={<UserOutlined style={{color: '#999', padding: '0 5px'}}/>}
                               size={"middle"}
                               onChange={(e) => changeSignAccount(e)}
                               value={SignAccount}
                               placeholder="账号 / 用户名"
                               allowClear
                        />
                    </Form.Item>

                    <Form.Item name="password" rules={
                        [{required: false},
                            () => ({
                                validator(_, value) {
                                    if (value === undefined ||value === null ||  value.length === 0){
                                        return Promise.reject(new Error('密码不能为空'));
                                    }
                                    /* 密码强度 */
                                    let passwordLevel = AuthPasswd(value);
                                    switch (passwordLevel) {
                                        case -1:
                                            return Promise.reject(new Error('请输入8位及以上的密码'));
                                        case 0:
                                            return Promise.reject(new Error('密码强度太弱！'));
                                        case 1:
                                            return Promise.resolve();
                                        case 2:
                                            return Promise.resolve();
                                        case null:
                                            return Promise.resolve();
                                    }
                                },
                            })
                        ]
                    }
                               hasFeedback
                    >
                        <Input.Password
                            maxLength={20}
                            size={"middle"}
                            type="password"
                            prefix={<LockOutlined style={{color: '#999', padding: '0 5px'}}/>}
                            onChange={(e) => changeSignPassword(e)}
                            value={SignPassword}
                            placeholder="登陆密码"
                            allowClear
                        />
                    </Form.Item>

                    <Form.Item
                        name="sure-password"
                        rules={
                            [
                                {required: false},
                                ({getFieldValue}) => ({
                                    validator(_, value) {
                                        if (value === undefined || value === null || value.length === 0){
                                            return Promise.reject(new Error('确认密码不能为空！'));
                                        } if (value && getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次密码输入不一致，请确认后再试！'));
                                    },
                                }),
                            ]
                        }
                        hasFeedback
                    >
                        <Input.Password
                            size={"middle"}
                            maxLength={20}
                            type="password"
                            prefix={<LockOutlined style={{color: '#999', padding: '0 5px'}}/>}
                            onChange={(e) => changeSignSurePassword(e)}
                            value={SignSurePassword}
                            placeholder="再次确认密码"
                            allowClear
                        />
                    </Form.Item>

                    <Form.Item name="mobile"
                               rules={
                                   [
                                       {required: false},
                                       ({getFieldValue}) => ({
                                           validator(_, value) {
                                               if (value === undefined || value === null || value.length === 0){
                                                   return Promise.reject(new Error('手机号不能为空！'));
                                               }else if (!isPhone(value)) {
                                                   return Promise.reject(new Error('手机号格式不正确！'));
                                               }
                                               return Promise.resolve();
                                           },
                                       }),
                                   ]
                               }
                               hasFeedback
                    >
                        <Input prefix={<MobileOutlined style={{color: '#999', padding: '0 5px'}}/>}
                               onChange={(e) => changeSignPhone(e)}
                               value={SignPhone}
                               size={"middle"}
                               placeholder="手机号码"
                               allowClear
                        />
                    </Form.Item>


                    <Form.Item name="email"
                               rules={
                                   [
                                       {required: false},
                                       ({getFieldValue}) => ({
                                           validator(_, value) {
                                               if (value === undefined || value === null || value.length === 0){
                                                   return Promise.reject(new Error('邮箱不能为空！'));
                                               }else if (!isEmail(value)) {
                                                   return Promise.reject(new Error('邮箱格式不正确！'));
                                               }
                                               return Promise.resolve();
                                           },
                                       }),
                                   ]
                               }
                    >
                        <Input prefix={<MailOutlined style={{color: '#999', padding: '0 5px'}}/>}
                               onChange={(e) => changeSignEmail(e)}
                               value={SignEmail}
                               size={"middle"}
                               placeholder={'电子邮箱'}
                               allowClear
                               addonAfter = {
                                   <span style={
                                       {
                                           borderColor: this.state.emailCodeTimeOut !== null || !isEmail(SignEmail) ? '#aaaaaa' : '#43a0ff',
                                           color: this.state.emailCodeTimeOut !== null || !isEmail(SignEmail) ? '#6f6f6f' : '#43a0ff',
                                           cursor: this.state.emailCodeTimeOut !== null || !isEmail(SignEmail) ? "no-drop" : 'pointer'
                                       }
                                   }
                                         onClick={this.state.emailCodeTimeOut !== null || !isEmail(SignEmail) ? null : this.handleSendEmailCode}>
                                       {
                                           this.state.emailCodeTimeOut === null ?
                                               "获取验证码" : `已发送(${this.state.emailCodeTimeOut}s)`
                                       }
                                   </span>
                               }
                        />
                    </Form.Item>

                    <Form.Item name="mailCode" rules={
                        [{required: true, message: '邮箱验证码不能为空！'}]
                    }>
                        <Input prefix={<NumberOutlined style={{color: '#999', padding: '0 5px'}}/>}
                               onChange={(e) => changeSignMailCode(e)}
                               value={SignMailCode}
                               size={"middle"}
                               placeholder={'邮箱验证码'}
                               allowClear
                        />
                    </Form.Item>

                    <Button style={{width: '100%', background: '#3B78DD', borderRadius: '10px'}}
                            htmlType="submit"
                            type="primary" onClick={() => Sign()}>立即注册</Button>
                </Form>
            </Fragment>
        )
    }


}

const mapStateToProps = (state) => {
    return {
        SignAccount: state.getIn(['login', 'SignInfo', 'account']),
        SignPassword: state.getIn(['login', 'SignInfo', 'password']),
        SignSurePassword: state.getIn(['login', 'SignInfo', 'SurePassword']),
        SignPhone: state.getIn(['login', 'SignInfo', 'phone']),
        SignEmail: state.getIn(['login', 'SignInfo', 'email']),
        SignSMSCode: state.getIn(['login', 'SignInfo', 'SMSCode']),
        SignMailCode: state.getIn(['login', 'SignInfo', 'mailCode']),
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        changeSignAccount(e) {
            dispatch(actions.handleSignAccount(e.target.value))
        },
        changeSignPassword(e) {
            dispatch(actions.handleSignPassword(e.target.value || ''))
        },
        changeSignSurePassword(e) {
            console.log(e)
            dispatch(actions.handleSignSurePassword(e.target.value))
        },
        changeSignPhone(e) {
            dispatch(actions.handleSignPhone(e.target.value))
        },
        changeSignEmail(e) {
            dispatch(actions.handleSignEmail(e.target.value))
        },
        changeSignSMSCode(e) {
            dispatch(actions.handleSignSMSCode(e.target.value))
        },
        changeSignMailCode(e) {
            dispatch(actions.handleSignMailCode(e.target.value))
        },
        handleSign() {
            dispatch(UserAction.SignUser());
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(SignView);
